package com.lsh.radardemo;

import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class RadarView extends View {
    private final Paint pointPaint = new Paint();
    private final Paint gridPaint = new Paint();
    private final Paint centerPaint = new Paint();
    private final Paint scanPaint = new Paint();

    private float maxDistance = 10.0f;
    private float scaleFactor = 1f;

    // 修改点集合类型（提升并发性能）
    private final List<PointF> points = new ArrayList<>();

    private final ScaleGestureDetector scaleDetector;
    private float scanRadius = 0f;

    public RadarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
        scaleDetector = new ScaleGestureDetector(context, new ScaleListener());

        // 启动扫描动画
        post(scanRunnable);
    }

    private void init() {
        // 黑色背景初始化
        setBackgroundColor(Color.BLACK);
        
        // 雷达点（白色，直径6px）
        pointPaint.setColor(Color.WHITE);
        pointPaint.setStrokeWidth(6f); // 加粗显示
        pointPaint.setStyle(Paint.Style.FILL);
        pointPaint.setAntiAlias(true);

        // 网格（浅灰色）
        gridPaint.setColor(0x44FFFFFF); // 半透明白
        gridPaint.setStrokeWidth(1.2f);
        gridPaint.setStyle(Paint.Style.STROKE);
        gridPaint.setAntiAlias(true);

        // 中心红点（增强对比度）
        centerPaint.setColor(0xFFFF3333); // 高饱和度红色
        centerPaint.setStyle(Paint.Style.FILL);
        centerPaint.setAntiAlias(true);

        // 扫描波（高对比度青色）
        scanPaint.setColor(Color.argb(80, 0, 255, 255)); // 增强透明度
        scanPaint.setStrokeWidth(2.5f);
        scanPaint.setAlpha(220); // 提升可见性
        scanPaint.setStyle(Paint.Style.STROKE);
        scanPaint.setAntiAlias(true);
    }

    // 修改 setPoints 方法（保留全部点）
    public void setPoints(List<PointF> newPoints) {
        if (newPoints == null || newPoints.isEmpty()) {
            postInvalidate();
            return;
        }
        
        // 直接全量替换（取消100点限制）
        points.clear();
        points.addAll(newPoints);
        
        // 异步重绘（避免阻塞主线程）
        postInvalidate();
    }

    public void setMaxDistance(float maxDistance) {
        this.maxDistance = maxDistance;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        
        // 自动缩放算法（保证所有点可见）
        float centerX = getWidth() / 2f;
        float centerY = getHeight() / 2f;
        
        // 动态计算最大距离
        float maxDataDistance = 0f;
        for (PointF point : points) {
            maxDataDistance = Math.max(maxDataDistance, 
                (float) Math.hypot(point.x, point.y));
        }
        
        // 自适应缩放因子（最小保证1米显示）
        float displayDistance = Math.max(maxDataDistance, 1.0f);
        float scale = Math.min(getWidth(), getHeight()) / (displayDistance * 2f) * scaleFactor;

        // 绘制坐标系
        drawGrid(canvas, centerX, centerY, scale);
        drawScanWave(canvas, centerX, centerY, scale);

        // 绘制雷达点（增强抗锯齿）
        if (!points.isEmpty()) {
            for (PointF point : points) {
                if (Float.isNaN(point.x) || Float.isNaN(point.y)) continue;
                
                float px = centerX + point.x * scale;
                float py = centerY - point.y * scale;
                
                if (Float.isInfinite(px) || Float.isInfinite(py)) continue;
                
                // 使用硬件加速优化
                canvas.drawCircle(px, py, 3f, pointPaint);
            }
        }
        
        // 强化中心点显示
        canvas.drawCircle(centerX, centerY, 8f, centerPaint);
    }

    private void drawGrid(Canvas canvas, float cx, float cy, float scale) {
        // 绘制十字坐标系
        canvas.drawLine(0, cy, getWidth(), cy, gridPaint);
        canvas.drawLine(cx, 0, cx, getHeight(), gridPaint);
        
        // 动态生成环形网格（最多10层）
        int ringCount = Math.min((int)maxDistance, 10);
        for (int i = 1; i <= ringCount; i++) {
            float r = i * maxDistance * scale / ringCount;
            canvas.drawCircle(cx, cy, r, gridPaint);
        }
        
        // 添加方向刻度（增强方向感）
        drawDirectionMarkers(canvas, cx, cy, scale);
    }

    private void drawDirectionMarkers(Canvas canvas, float cx, float cy, float scale) {
        // 绘制方向刻度（0°/90°/180°/270°）
        float markerLength = 10f;
        for (int angle : new int[]{0, 90, 180, 270}) {
            double rad = Math.toRadians(angle);
            float x1 = cx + (float)(maxDistance * scale * Math.cos(rad));
            float y1 = cy - (float)(maxDistance * scale * Math.sin(rad));
            canvas.drawLine(cx, cy, x1, y1, gridPaint);
            
            // 添加方向文字
            canvas.drawText(
                String.valueOf(angle) + "°", 
                x1 + (float)Math.cos(rad)*12, 
                y1 - (float)Math.sin(rad)*12,
                gridPaint
            );
        }
    }

    private void drawScanWave(Canvas canvas, float cx, float cy, float scale) {
        float r = scanRadius * scale;
        canvas.drawCircle(cx, cy, r, scanPaint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return scaleDetector.onTouchEvent(event) || super.onTouchEvent(event);
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            scaleFactor *= detector.getScaleFactor();
            scaleFactor = Math.max(0.5f, Math.min(scaleFactor, 3.0f)); // 限制缩放范围
            invalidate();
            return true;
        }
    }

    private final Runnable scanRunnable = new Runnable() {
        @Override
        public void run() {
            scanRadius += 0.1f;
            if (scanRadius > maxDistance) {
                scanRadius = 0f;
            }
            invalidate();
            postDelayed(this, 30); // 每30ms更新一次
        }
    };
}
